/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.majc.travelapplication.DB;

import edu.chl.majc.travelapplication.core.Customer;
import edu.chl.majc.travelapplication.core.Customer_;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author lujoel
 */
@Stateless
public class JPACustomerController implements Serializable {

    @PersistenceContext(unitName = "travel_pu")
    private EntityManager em;

    public JPACustomerController() {
    }

    public void create(Customer entity) {
        //em = Persistence.createEntityManagerFactory("travel_pu").createEntityManager();

        /*if(em == null){
        System.out.println("em is nullcvvvvvvvvvvvvvvvvvv");
        em = Persistence.createEntityManagerFactory("travel_pu").createEntityManager();
        
        }*/
        em.persist(entity);
    }

    public void edit(Customer entity) {
        em.merge(entity);
    }

    public void remove(Customer entity) {
        em.remove(em.merge(entity));
    }

    public Customer find(String id) {
        return em.find(Customer.class, id);
    }

    public List<Customer> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Customer.class));
        return em.createQuery(cq).getResultList();
    }

    public List<Customer> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Customer.class));
        javax.persistence.Query q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<Customer> rt = cq.from(Customer.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        javax.persistence.Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

    public Customer getByEmail(String email) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
        Root<Customer> cu = query.from(Customer.class);
        query.where(builder.equal(cu.get(Customer_.email),email));
        javax.persistence.Query q = em.createQuery(query);
        System.out.println("getbyemail query result: " + q.getSingleResult());
        return (Customer) q.getSingleResult();
    }
}
